package com.sunday.fangbeibei.tool;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.sunday.fangbeibei.http.HttpResponseInterface;
import com.sunday.fangbeibei.http.HttpTool;
import com.sunday.fangbeibei.orm.BaseResult;
import com.sunday.fangbeibei.orm.UpdateInfo;

/**
 * 

* @ClassName: VersionUtil 

* @Description: TODO(版本检测工具) 

* @author sunshineHu hucx@itouch.com.cn

* @date 2015年1月16日 下午12:32:59 

*
 */
public class VersionUpdate extends Handler implements HttpResponseInterface{

	private WeakReference<Context> contextReference;//弱引用
	private boolean isSilent;
	
	public VersionUpdate(Context c) {
		// TODO Auto-generated constructor stub
		contextReference=new WeakReference<Context>(c);
	}
	
	
	public void checkVersion(boolean isSilent){
		this.isSilent=isSilent;
		
		RequestParams params=new RequestParams();
		params.add("appcode", "fbb");
		HttpTool.HttpPost(0, contextReference.get(), "http://test.sunday-mobi.com:9216/apps/getVersion", params, this, new TypeToken<BaseResult<UpdateInfo>>() {}.getType());
		
	}

	@Override
	public void onResponse(int resultCode,boolean resultStatus, Object result) {
		// TODO Auto-generated method stub
		BaseResult<UpdateInfo> result0=(BaseResult<UpdateInfo>) result;
		try {
			if(result0.getResult().getVersion().equals(getVersionName())){
				sendEmptyMessage(0x444555);
			}else{
				Message msg = this.obtainMessage();
				msg.obj=result0.getResult();
				msg.what = 0x111222;
				this.sendMessage(msg);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.sendEmptyMessage(0x999999);
		}
	}

	@Override
	public void onFailure() {
		// TODO Auto-generated method stub
		this.sendEmptyMessage(0x222333);
	}


	 
	/*
	 * 获取当前程序的版本号 
	 */
	private String getVersionName() throws Exception{
		//获取packagemanager的实例 
		PackageManager packageManager = contextReference.get().getPackageManager();
		//getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(contextReference.get().getPackageName(), 0);
	    return packInfo.versionName; 
	}
	
	
	
	
		
	@Override
	public void handleMessage(Message msg) {
		// TODO Auto-generated method stub
		super.handleMessage(msg);
		if(contextReference.get()==null){//应用为空
			return;
		}
		switch (msg.what) {
		case 0x111222:
			//对话框通知用户升级程序
			UpdateInfo info=(UpdateInfo) msg.obj;
			showUpdataDialog(info);
			break;
		case 0x222333:
			if(!isSilent){
				Toast.makeText(contextReference.get(), "获取服务器更新信息失败", Toast.LENGTH_SHORT).show();
			}
			break;	
		case 0x333444:
			Toast.makeText(contextReference.get(), "下载新版本失败", Toast.LENGTH_SHORT).show();
			break;	
		case 0x444555:
			if(!isSilent){
				Toast.makeText(contextReference.get(), "您使用的是最新版本，无需更新！", Toast.LENGTH_SHORT).show();
			}
			break;	
		case 0x999999:
			Toast.makeText(contextReference.get(), "获取版本信息失败！", Toast.LENGTH_SHORT).show();
			break;	
		}
	}
	
	/*
	 * 
	 * 弹出对话框通知用户更新程序 
	 * 
	 * 弹出对话框的步骤：
	 * 	1.创建alertDialog的builder.  
	 *	2.要给builder设置属性, 对话框的内容,样式,按钮
	 *	3.通过builder 创建一个对话框
	 *	4.对话框show()出来  
	 */
	protected void showUpdataDialog(final UpdateInfo info) {
		if(contextReference.get()==null){
    		return;
    	}
		AlertDialog.Builder builer = new Builder(contextReference.get()) ; 
		builer.setTitle("版本升级");
		builer.setMessage("发现新版本v"+info.getVersion()+"，是否更新？");
		//当点确定按钮时从服务器上下载 新的apk 然后安装 
		builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
				downLoadApk(info);
			}   
		});
		//当点取消按钮时进行登录
		builer.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		AlertDialog dialog = builer.create();
		dialog.show();
	}
	
	/*
	 * 从服务器中下载APK
	 */
	protected void downLoadApk(final UpdateInfo info) {
		if(contextReference.get()==null){
    		return;
    	}
		final ProgressDialog pd;	//进度条对话框
		pd = new  ProgressDialog(contextReference.get());
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载更新");
		pd.setCanceledOnTouchOutside(false);
		pd.show();
		new Thread(){
			@Override
			public void run() {
				try {
					File file = getFileFromServer(info.getFilePath(), pd,contextReference.get());
					sleep(3000);
					installApk(file);
					pd.dismiss(); //结束掉进度条对话框
				} catch (Exception e) {
					sendEmptyMessage(0x333444);
				}
			}}.start();
	}
	
	//安装apk 
	protected void installApk(File file) {
		if(contextReference.get()==null){
    		return;
    	}
		Intent intent = new Intent();
		//执行动作
		intent.setAction(Intent.ACTION_VIEW);
		//执行的数据类型
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		contextReference.get().startActivity(intent);
	}
	
    
    public static File getFileFromServer(String path, ProgressDialog pd,Context c) throws Exception{

		//如果相等的话表示当前的sdcard挂载在手机上并且是可用的

		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

			URL url = new URL(path);

			HttpURLConnection conn =  (HttpURLConnection) url.openConnection();

			conn.setConnectTimeout(5000);

			//获取到文件的大小 

			pd.setMax(conn.getContentLength()/1024);

			InputStream is = conn.getInputStream();

			File file = new File(Environment.getExternalStorageDirectory(), "fbb.apk");

			FileOutputStream fos = new FileOutputStream(file);

			BufferedInputStream bis = new BufferedInputStream(is);

			byte[] buffer = new byte[1024];

			int len ;

			int total=0;

			while((len =bis.read(buffer))!=-1){

				fos.write(buffer, 0, len);

				total+= len;

				//获取当前下载量

				pd.setProgress(total/1024);

			}

			fos.close();

			bis.close();

			is.close();

			return file;

		}

		else{
			/**
			 * 保存到手机内存
			 */
			URL url = new URL(path);

			HttpURLConnection conn =  (HttpURLConnection) url.openConnection();

			conn.setConnectTimeout(5000);

			//获取到文件的大小 

			pd.setMax(conn.getContentLength());

			InputStream is = conn.getInputStream();
			FileOutputStream outStream = null;
			   try {
				    outStream = c.openFileOutput("fbb.apk", Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE);
				    int temp = 0;
				    byte[] data = new byte[1024];
					int total=0;
				    while ((temp = is.read(data)) != -1) {
				     outStream.write(data, 0, temp);
					 total+= temp;
					 //获取当前下载量
					 pd.setProgress(total);
				    }
				    outStream.flush();
				    outStream.close();
				    is.close();
			    }catch (Exception e) {
					// TODO: handle exception
			    	return null;
			    }
			
			return c.getFileStreamPath("fbb.apk");

		}

	}


}
